package com.sugon.stream;

import org.junit.Test;
import java.util.function.Predicate;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;

/**
 * 数值流
 */
public class TestStream_intstream {

	public static void main(String[] args) {
		
		//创建数值流
		IntStream is = IntStream.range(1, 100);  // 1-99        [1,100)
		//求和
		System.out.println(is.sum());
		//闭区间
		IntStream is2 = IntStream.rangeClosed(1, 100); //1-100  [1,100]
		System.out.println(is2.sum());

		/**
		 * 判断一个数是否质数
		 */
		Predicate<Integer> p1 = new Predicate<Integer>(){
			public boolean test(Integer n){
				for(int i = 2 ; i <= Math.sqrt(n);i++){
					if (n % i == 0) return false;
				}
				return true;
			}
		};

		Predicate<Integer> p2 = n->{
			//从2开始
			IntStream ist = IntStream.rangeClosed(2, (int)Math.sqrt(n));
			//
			return ist.noneMatch(i->n%i==0);
		};
		
		System.out.println(p2.test(100));
		System.out.println(p2.test(101));

	}

    /**
     * 迭代计算，可以创建无限流
     */
	@Test
	public void test(){
		int x = 8;
		//无限流
		IntStream stream = IntStream.iterate(2, i->i+1);
		int result = stream.filter(n->{
			IntStream ist = IntStream.rangeClosed(2, (int)Math.sqrt(n));
			return ist.noneMatch(i->n%i==0);
		}).skip(x-1).findFirst().getAsInt();

		System.out.println(result);
		//DoubleStream stream2 = DoubleStream.generate(Math::random);
	}


}
